import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { Spin } from 'antd';
import { DataNode } from 'antd/lib/tree';
import { xhr_get, xhr_post_json } from '../_common/request';
import BasicTree, { BasicTreeProps } from './basic-tree';

interface SearchTreeProps extends BasicTreeProps {
  api?: {
    url: string;
    params?: object;
    type?: 'GET' | 'POST';
  }, // 接口参数
  outerNode?: DataNode; // 最外层节点
  keyName?: string; // 请求数据的key名称
  titleName?: string; // 请求数据的title名称
  children?: React.ReactNode;
  titleWithKey?: boolean; // 是否显示 title + key
  [key: string]: any; // 添加其他属性
}

interface ResultData {
  isLeaf?: boolean;
  children?: ResultData[];
  [key: string]: any;
}

export const transformTreeData = (data: ResultData[], keyName: string, titleName: string, titleWithKey: boolean, disabledFunc?: (it: ResultData) => boolean): DataNode[] => {
  return data.map((item: ResultData): DataNode => {
    return {
      ...item,
      key: item[keyName],
      title: (titleWithKey && item.selectable) ? item[keyName] + ' - ' + item[titleName] : item[titleName],
      isLeaf: item.isLeaf,
      children: item.children && transformTreeData(item.children, keyName, titleName, titleWithKey, disabledFunc),
      disabled: disabledFunc?.(item),
    };
  })
}
const SearchTree = (props: SearchTreeProps) => {
  const {
    api = {
      url: '',
      params: {},
      type: 'GET',
    },
    outerNode,
    keyName = 'key',
    titleName = 'title',
    treeData = [],
    children,
    titleWithKey = false,
    refreshFlag,
      disabledFunc,
    ...otherProps
  } = props;
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<DataNode[]>(treeData);

  useEffect(() => {
    if (api.url) {
      requestData();
    }
  }, [api.url, refreshFlag]);

  useEffect(() => {
    setDataSource(treeData);
  }, [JSON.stringify(treeData)])

  /**
   * 数据请求
   */
  const requestData = async () => {
    const xhr = !api.type || api.type === 'GET' ? xhr_get : xhr_post_json;

    try {
      setLoading(true);
      const res: any = await xhr(api.url, api.params);
      setLoading(false);
      if (res && res.success) {
        const data: DataNode[] = transformTreeData(res.result || [], keyName, titleName, titleWithKey, disabledFunc);

        if (outerNode) {
          outerNode.children = data;
          setDataSource([outerNode]);
        } else {
          setDataSource(data);
        }
      }
    } catch (err) {
      console.log(err);
    }
  }

  return (
    <Spin spinning={loading}>
      {children}
      {
        dataSource?.length ? <BasicTree {...otherProps} treeData={dataSource} /> : null
      }
    </Spin>
  )
}

export default SearchTree;